package io.xccit.controller;

import io.xccit.entity.User;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PostFilter;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.access.prepost.PreFilter;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @author CH_ywx
 * @date 2023-06-04
 * @description
 */
@RestController
@RequestMapping("/test")
public class TestController {

    @GetMapping("/hello")
    public String hello(){
        return "Hello SpringSecurity!";
    }
    @Secured({"ROLE_admin","ROLE_sale"}) //角色为admin或sale可访问
    @GetMapping("/index")
    public String index(){
        return "Index";
    }

    @PreAuthorize("hasAnyAuthority('insert','save')") //有insert或save权限可访问
    @GetMapping("/insert")
    public String insert(){
        return "insert";
    }

//    @PreAuthorize("hasAnyRole('ROLE_admin','ROLE_sale')") //有admin或sale角色信息都可访问
    @PostAuthorize("hasAnyRole('ROLE_admin','ROLE_sale')") //有admin或sale角色都可访问
    @GetMapping("/update")
    public String update(){
        System.out.println("update()..........");
        return "update";
    }

    /**
     * 传入的数据做过滤
     * @return 传入的符合要求的数据
     */
    @PostAuthorize("hasAnyRole('ROLE_admin','ROLE_sale')") //有admin或sale角色都可访问
    @GetMapping("/save")
    @PreFilter("filterObject.id%2==0") //将id%2==0的数留下
    public String save(@RequestBody List<User> users){
        users.forEach(user -> {
            System.out.println(user.getId() + "\t" + user.getUsername());
        });
        return "save";
    }
    @PostAuthorize("hasAnyRole('ROLE_admin','ROLE_sale')") //有admin或sale角色都可访问
    @GetMapping("/getAll")
    @PostFilter("filterObject.username=='admin'") //只返回username为admin的数据
    public List<User> getAll(){
        ArrayList<User> users = new ArrayList<>();
        users.add(new User(1,"admin","admin"));
        users.add(new User(2,"admin1","admin"));
        users.add(new User(3,"admin2","admin"));
        return users;
    }
}
